import os
from django.http.response import StreamingHttpResponse
from django.utils.encoding import escape_uri_path
from rest_framework import permissions, filters, response, status
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from apps.product.report.models import ReportModel
from apps.product.report.serializers import ReportModelSerializer
from utils import mixins
from utils.common import get_report_content


class ReportViewSet(mixins.RetrieveModelMixin,
                    mixins.ListModelMixin,
                    GenericViewSet):
    queryset = ReportModel.objects.all()
    serializer_class = ReportModelSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['create_time']

    def retrieve(self, request, *args, **kwargs):
        """获取报告html"""
        result = super().retrieve(request, *args, **kwargs)
        del result.data["data"]["create_time"]
        del result.data["data"]["result"]
        del result.data["data"]["count"]
        del result.data["data"]["success"]
        del result.data["data"]["fail"]
        del result.data["data"]["summary"]
        del result.data["data"]["path"]
        return response.Response(result.data, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        """获取报告列表"""
        result = super().list(request, *args, **kwargs)
        for item in result.data["data"]["results"]:
            item["result"] = "succeed" if item["result"] == 0 else "failed"
            del item["content"]
            del item["path"]
        return response.Response(result.data, status=status.HTTP_200_OK)

    @action(methods=["GET"], detail=True)
    def download(self, request, *args, **kwargs):
        """下载报告"""
        report_obj = self.get_object()
        # 获取文件流
        if not os.path.exists(report_obj.path):
            os.makedirs(os.path.dirname(report_obj.path))
            with open(file=report_obj.path, mode="w", encoding="utf-8") as f:
                f.write(report_obj.content)
        file = StreamingHttpResponse(get_report_content(report_obj.path))
        # 解决中文乱码
        file_name = escape_uri_path(report_obj.name + ".html")
        # 返回给前端
        file["Content-Type"] = "application/octet-stream"
        file["Content-Disposition"] = f"attachment; filename*=UTF-8''{file_name}"
        return file
